var RepairTableBoard = function () {
  var template = /* html */ `
    <div class="repair-table-board" v-loading.fullscreen.lock="loading">
      <div class="repair-table-board-table-div" :class="{'has-page':totalPage>2}">
        <div ref="tableHead" class="table-board-header">
          <repair-table-item :repairs="repairList"></repair-table-item>
        </div>
        <div class="table-board-body">
          <el-scrollbar ref="scrollBar" :wrap-style="getScrollbarWrapStyle()">
            <div>
              <repair-table-item :repairs="repairList" @look-detail="lookDetail"></repair-table-item>
            </div>
          </el-scrollbar>
        </div>
      </div>
      <div class="repair-table-board-page" v-if="totalPage>2">
        <el-pagination background :page-size="pagination.pageSize" :total="pagination.totalCount" :current-page.sync="pagination.currentPage"
          @current-change="pageChange"></el-pagination>
      </div>

      <el-dialog title="工单详情" :visible.sync="openDialog" top="10vh" @closed="dialogClosed">
        <div style="height:calc(80vh - 54px);overflow:auto">
          <repair-table-detail v-if="openDialog" :detail="selectRepair"></repair-table-detail>
        </div>
      </el-dialog>
    </div>
  `;

  return {
    mixins: [boardRunningMixin],

    watch: {
      moveX: function (newVal) {
        var tableHead = this.$refs['tableHead'];
        if (tableHead === undefined) {
          return;
        }

        $(tableHead).scrollLeft(newVal);
      }
    },

    computed: {
      totalPage: function () {
        var pagination = this.pagination;
        var totalPage = pagination.totalCount / pagination.pageSize;
        totalPage = Math.ceil(_.round(totalPage, 2));
        return totalPage;
      }
    },

    data: function () {
      return {
        loading: false,
        repairList: [],
        pagination: {
          currentPage: 1,
          totalCount: 0,
          pageSize: 15
        },
        moveX: 0,
        openDialog: false,
        selectRepair: null,
        eventSource: null
      };
    },

    created: function () {
      var self = this;
      this.setRepairList().then(function () {
        self.boardRunning();
      });
    },

    mounted: function () {
      var $wrap = $(this.$refs['scrollBar'].$el).find('.el-scrollbar__wrap');
      $wrap.on('scroll', this.tableScroll);
      this.addRepairTableRunning();
    },

    beforeDestroy: function () {
      var eventSource = this.eventSource;
      if (eventSource !== null) {
        eventSource.close();
      }
    },

    methods: {
      setRepairList: function (hasLoading) {
        if (hasLoading === undefined) {
          hasLoading = true;
        }

        var pagination = this.pagination;
        var currentPage = pagination.currentPage;
        var pageSize = pagination.pageSize;
        var start = (currentPage - 1) * pageSize;

        var postData = {
          start: start,
          length: pageSize,
          status: -99,
          custPay: -99,
          watchBord: 1
        };

        if (hasLoading) {
          this.loading = true;
        }
        var self = this;
        return ajaxRequest('workOrder/getApplyList', postData, false).then(function (res) {
          var repairList = res.returnData;
          repairList = _.map(repairList, function (repair, index) {
            repair = new RepairTableInfo(repair);
            repair.rowIndex = index;
            return repair;
          });

          self.repairList = repairList;
          self.pagination.totalCount = res.iTotalRecords;
          if (hasLoading) {
            self.loading = false;
          }
          return repairList;
        }).catch(function () {
          if (hasLoading) {
            self.loading = false;
          }
          return [];
        });
      },

      addRepairTableRunning: function () {
        if (window.EventSource) {
          var basePath = SysUtil.getBasePath();
          var source = new EventSource(basePath + '/sse/workOrder/addApplyWorkOrder');
          s = ' ';
          var self = this;
          source.addEventListener('message', function (e) {
            if (e.data.length > 0) {
              $("#audio_1").remove();
              $("body").append(
                '<audio id="audio_1" src="https://upload.shinehao.com.cn/mp3/newWorkOrder.mp3" controls autoplay hidden></audio>');
              self.pagination.totalCount = 1;
              self.clearTimeoutList();
              self.resetTable(false).then(function () {
                self.boardRunning();
              });
            }
          });

          source.addEventListener('error', function (e) {
            if (e.readyState === EventSource.CLOSED) {
              console.log("Connection is closed");
            }
          }, false);
          self.eventSource = source;
        } else {
          this.$alert("Your web browser dosen't support EventSource.");
        }
      },

      pageChange: function () {
        this.clearTimeoutList();
        var self = this;
        this.resetTable().then(function () {
          self.boardRunning();
        });
      },

      getScrollbarWrapStyle: function () {
        var width = SysUtil.getScrollbarWidth();
        return [{
          width: `calc(100% + ${width}px)`,
          height: `calc(100% + ${width}px)`
        }];
      },

      resetTable: function (isLoading) {
        var self = this;
        return this.setRepairList(isLoading).then(function (repairList) {
          self.tableScroll();
          return repairList;
        });
      },

      tableScroll: function () {
        var scrollBar = this.$refs['scrollBar'];
        var moveX = 0;
        if (scrollBar !== undefined) {
          moveX = scrollBar.moveX;
          var width = $(scrollBar.$el).find('.el-scrollbar__wrap').width();
          moveX = moveX * width / 100;
        }
        this.moveX = moveX;
      },

      boardRunning: function () {
        this.clearTimeoutList();

        this.resetRepairTableRunning();
      },

      resetRepairTableRunning: function () {
        var self = this;
        var timeout = setTimeout(function () {
          self.resetTable(false).then(function () {
            self.resetRepairTableRunning();
          });
          self.timeoutList[0] = null;
        }, 5 * 1000);
        this.timeoutList[0] = timeout;
      },

      lookDetail: function (repair) {
        this.selectRepair = repair;
        this.openDialog = true;
      },

      dialogClosed: function () {
        this.openDialog = false;
      }
    },

    components: {
      RepairTableItem: RepairTableItem,
      RepairTableDetail: RepairTableDetail
    },

    template: template
  };
}();
